package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY))
    public void listenVerifyCodeMesage(Map<String,String> msg){
//          代码健壮性判断
        if(CollectionUtils.isEmpty(msg)){
//            如果短信内容为空，不做处理
            return;
        }
//      手机号
        String phone = msg.get("phone");
        if(!RegexUtils.isPhone(phone)){
//            手机号有误，不处理
            return;
        }
//      验证码
        String code = msg.get("code");
        if(!RegexUtils.isCodeValid(code)){
//            验证码有误，不处理
            return;
        }

//        发送短信
        try {
            smsUtils.sendVerifyCode(phone, code);
        } catch (Exception e) {
//            短信发送失败,这里捕获后MQ就不会一直发送短信请求
            log.error("sms短信验证码发送失败", e);

        }
    }


}
